package callbacks;

import java.util.concurrent.Callable;

import models.YouUser;
import models.YouUser.FacebookData;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;

import play.libs.Akka;
import play.libs.F;
import play.libs.F.Function;
import play.libs.F.Promise;
import play.libs.WS;
import play.libs.WS.Response;
import services.FacebookQueryService;

public class FacebookCallbacks {
	public static class GetInfo implements Function<WS.Response,Promise<FacebookData>> {
		public Promise<FacebookData> apply(Response arg0) throws Throwable {
			if (arg0.getBody().startsWith("access_token=")) {
				final String accessToken = arg0.getBody().split("[=&]")[1];
				Promise<JsonNode> users = FacebookQueryService.getUserData(accessToken);
				return users.flatMap(new Function<JsonNode, F.Promise<FacebookData>>() {
					
					@Override
					public Promise<FacebookData> apply(final JsonNode data) throws Throwable {
						ObjectMapper mapper = new ObjectMapper();
						final FacebookData fbdata = mapper.readValue(data, FacebookData.class);
						fbdata.accessToken = accessToken;
						return Akka.future(new Callable<FacebookData>() {
							
							@Override
							public FacebookData call()	throws Exception {
								return fbdata;
							}
						});
					}
				});
			} else {
				throw new RuntimeException("error retrieving accessToken");
			}
		}
	}
	
	public static class PopulateUserObject implements Function<FacebookData,YouUser> {

		YouUser user;
		public PopulateUserObject(YouUser user) {
			this.user = user;
		}
		
		@Override
		public YouUser apply(FacebookData data) throws Throwable {
			user.updateFacebookData(data);
			return user;
		}
		
	}
}